package com.cloud.pole.weixin.wechat;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.cloud.pole.common.util.DateUtils;
import com.cloud.pole.weixin.wechat.domain.AddMaterialRespMsg;
import java.io.*;

import lombok.extern.slf4j.Slf4j;

/*
*2019年5月12日
*cloud-weixin
*author:frank-chen
*/
@Slf4j
public class MaterialService {
	/**
	 * 媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
	 */
	public static final String FILE_TYPE_IMAGE = "image";
	public static final String FILE_TYPE_VOICE = "voice";
	public static final String FILE_TYPE_VIDEO = "video";
	public static final String FILE_TYPE_THUMB = "thumb";

	/**
	 * 新增其他类型永久素材
	 */
	public static AddMaterialRespMsg addMaterial(String accessToken, String fileUrl) {
		File imageFile = null;
		AddMaterialRespMsg respMsg = null;
		try {
			imageFile = new File(fileUrl);
			int pot= fileUrl.lastIndexOf(".");        
			String extName = fileUrl.substring(pot + 1);  
			String fileType = "";
			if(StringUtils.equalsIgnoreCase(extName, "bmp") || StringUtils.equalsIgnoreCase(extName, "png") || StringUtils.equalsIgnoreCase(extName, "jpeg") 
					|| StringUtils.equalsIgnoreCase(extName, "jpg") || StringUtils.equalsIgnoreCase(extName, "gif")) {
				fileType = FILE_TYPE_IMAGE;
			}
			else if(StringUtils.equalsIgnoreCase(extName, "mp3") || StringUtils.equalsIgnoreCase(extName, "wma") 
					|| StringUtils.equalsIgnoreCase(extName, "wav") || StringUtils.equalsIgnoreCase(extName, "amr")) {
				fileType = FILE_TYPE_VOICE;
			}
			else if(StringUtils.equalsIgnoreCase(extName, "mp4")) {
				fileType = FILE_TYPE_VIDEO;
			}
			else if(StringUtils.equalsIgnoreCase(extName, "thumb")) {
				fileType = FILE_TYPE_THUMB;
			}
			else {
				log.error("extName["+ extName +"] 错误");
				return null;
			}
			String result = null;
			if (imageFile.exists() && imageFile.isFile()) {
				String strURL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + accessToken
						+ "&type=" + fileType;
		        URL urlObj = new URL(strURL);

				// 创建Http连接
				HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
				conn.setRequestMethod("POST");
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.setUseCaches(false); // 使用post提交需要设置忽略缓存

				// 消息请求头信息
				conn.setRequestProperty("Connection", "Keep-Alive");
				conn.setRequestProperty("Charset", "UTF-8");

				// 设置边界
				String BOUNDARY = "----------" + System.currentTimeMillis();
				conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

				StringBuilder sb = new StringBuilder();
				sb.append("--"); // 必须多两道线
				sb.append(BOUNDARY);
				sb.append("\r\n");
				sb.append("Content-Disposition:form-data;name=\"media\";filename=\"" + imageFile.getName()
						+ "\";filelength=\"" + imageFile.length() + "\"\r\n");
				sb.append("Content-Type:application/octet-stream\r\n\r\n");

				byte[] head = sb.toString().getBytes("utf-8");

				// 创建输出流
				OutputStream out = new DataOutputStream(conn.getOutputStream());
				// 获得输出流表头
				out.write(head);

				// 文件正文部分
				DataInputStream in = new DataInputStream(new FileInputStream(imageFile));
				int bytes = 0;
				byte[] bufferOut = new byte[1024 * 1024 * 10]; // 10M
				while ((bytes = in.read(bufferOut)) != -1) {
					out.write(bufferOut, 0, bytes);
				}
				in.close();

				// 结尾
				byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
				out.write(foot);
				out.flush();
				out.close();

				// 获取响应
				StringBuffer buffer = new StringBuffer();
				BufferedReader reader = null;
				try {
					reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line = null;
					while ((line = reader.readLine()) != null) {
						buffer.append(line);
					}
					if (result == null) {
						result = buffer.toString();
					}
				} catch (IOException e) {
					log.error(e.toString());
					e.printStackTrace();
				} finally {
					reader.close();
				}
			}
			log.info("addMaterial RespMsg is:\n" + result + "\n");
			respMsg = JSON.parseObject(result, AddMaterialRespMsg.class);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			log.error("addMaterial excep: " + e.toString());
		}
		return respMsg;
	}

	/**
	 * 新增临时素材
	 */
	public static AddMaterialRespMsg addTemporaryMaterial(String accessToken, String fileUrl) {
		HttpClient client = null;
		PostMethod postMethod = null;
		File imageFile = null;
		int nStatus = 0;
		String strResp = "", strMediaID = "";
		AddMaterialRespMsg respMsg = null;
		try {
			int pot= fileUrl.lastIndexOf(".");        
			String extName = fileUrl.substring(pot + 1);  
			String fileType = "";
			if(StringUtils.equalsIgnoreCase(extName, "bmp") || StringUtils.equalsIgnoreCase(extName, "png") 
					|| StringUtils.equalsIgnoreCase(extName, "jpeg") 
					|| StringUtils.equalsIgnoreCase(extName, "jpg") || StringUtils.equalsIgnoreCase(extName, "gif")) {
				fileType = FILE_TYPE_IMAGE;
			}
			else if(StringUtils.equalsIgnoreCase(extName, "amr") || StringUtils.equalsIgnoreCase(extName, "mp3")) {
				fileType = FILE_TYPE_VOICE;
			}
			else if(StringUtils.equalsIgnoreCase(extName, "mp4")) {
				fileType = FILE_TYPE_VIDEO;
			}
			else if(StringUtils.equalsIgnoreCase(extName, "thumb")) {
				fileType = FILE_TYPE_THUMB;
			}
			String strURL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=" + fileType;
			client = new HttpClient();
			postMethod = new PostMethod(strURL);
			imageFile = new File(fileUrl);

			Part[] parts = { new FilePart(imageFile.getName(), imageFile) };

			postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

			nStatus = client.executeMethod(postMethod);
			if (nStatus != 200) {
				log.info("addTemporaryMaterial error - Status[" + nStatus + "]");
			}
			strResp = postMethod.getResponseBodyAsString();
			postMethod.releaseConnection();
			log.info("addTemporaryMaterial RespMsg is:\n" + strResp + "\n");
			respMsg = JSON.parseObject(strResp, AddMaterialRespMsg.class);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			log.error("addTemporaryMaterial excep: " + e.toString());
		}
		return respMsg;
	}

	public static void main(String[] args) {
		String token = "21_3r8RAEOtEOh9Kk0P7xkkcXFt4nl01i6yLsN8GKEisAjeW6kZogQ38uF22UPvk8OgrecSsC44mfuPWgnnxFI-uuHFG2nPbf3KDRDG6YRrvyrs6ltwNx4fo9-ykYQRCKiAGALWE";
//		MaterialService.addMaterial(token, "D:\\qrcode_for_gh_a162fab30df0_1280.jpg");
		MaterialService.addTemporaryMaterial(token, "D:\\qrcode_for_gh_a162fab30df0_1280.jpg");
	}
}
